package com.donald.videoHub.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donald.videoHub.entity.R;
import com.donald.videoHub.entity.Video;
import com.donald.videoHub.entity.VideoPlayer;
import com.donald.videoHub.service.ActorService;
import com.donald.videoHub.service.VideoGenreService;
import com.donald.videoHub.service.VideoPlayerService;
import com.donald.videoHub.service.VideoService;
import com.donald.videoHub.util.VideoFileScanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class Controller {

    private static final Logger log = LogManager.getLogger(Controller.class);

    @Resource
    VideoService service;

    @Resource
    VideoGenreService genreService;

    @Resource
    ActorService actorService;

    @Resource
    VideoPlayerService playerService;

    @PostMapping
    public R list(@RequestBody Video query) {
        LambdaQueryWrapper<Video> wrp = new LambdaQueryWrapper<>();
        // 标题
        wrp.like(StringUtils.isNotBlank(query.getTitle()), Video::getTitle, query.getTitle())
                // 评分
                .eq(ObjectUtils.isNotEmpty(query.getRate()), Video::getRate, query.getRate())
                // 磁盘
                .likeRight(ObjectUtils.isNotEmpty(query.getDisk()), Video::getPath, query.getDisk())
                // 开关
                .eq(Video::getInlegal, query.getInlegal());

        // 同时匹配都匹配类型
        wrp.and(ArrayUtils.isNotEmpty(query.getMultiGenre()), w -> {
            for (String s : query.getMultiGenre()) {
                w.like(Video::getGenre, s);
            }
        });

        // 同时匹配都匹配类型
        wrp.and(ArrayUtils.isNotEmpty(query.getMultiActor()), w -> {
            for (String s : query.getMultiActor()) {
                w.like(Video::getActorName, s);
            }
        });

        Page<Video> page = new Page<>();
        page.setSize(query.getPageSize());
        page.setCurrent(query.getCurrentPage());

        if (StringUtils.isNotBlank(query.getOrder())) {
            boolean asc = StringUtils.startsWith(query.getOrder(), "asc");
            page.addOrder(new OrderItem(StringUtils.lowerCase(StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(query.getProp()), "_")), asc));
        }
        Page<Video> resPage = service.page(page, wrp);
        resPage.getRecords().forEach(e -> {
            if (StringUtils.isNotBlank(e.getActorName())) {
                e.setMultiActor(e.getActorName().split(","));
            }
            if (StringUtils.isNotBlank(e.getGenre())) {
                e.setMultiGenre(e.getGenre().split(","));
            }
        });
        return R.ok(resPage);
    }

    @GetMapping("/scan")
    public R scan(String path) {
        log.info("path:{}", path);
        String res = VideoFileScanner.start(service).scanDirectory(path);
        return R.ok(res);
    }

    @GetMapping("/diskPath")
    public R getDiskPath() {
        String[] diskPath = VideoFileScanner.start(service).getDiskPath();
        return R.ok(diskPath);
    }

    @GetMapping("/clear")
    public R clear() {
        service.remove(new LambdaQueryWrapper<>());
        return R.ok();
    }

    @GetMapping("/save")
    public R save(Video v) {
        log.info("v:{}", v);
        service.save(v);
        return R.ok();
    }

    @PostMapping("/update")
    public R update(@RequestBody Video v) {
        log.info("v:{}", v);
        service.updateById(v);
        return R.ok();
    }

    @PostMapping("/play")
    public R play(@RequestBody Video v) throws IOException {
        String path = playerService.getById(1).getPath();
        Runtime.getRuntime().exec(path + " " + v.getPath());
        return R.ok();
    }

    @GetMapping("/genre")
    public R genre() throws IOException {
        return R.ok(genreService.list());
    }

    @GetMapping("/actor")
    public R actor() throws IOException {
        return R.ok(actorService.list());
    }

    @PostMapping("/rm")
    public R rm(@RequestBody Video v) throws IOException {
        if (service.removeById(v)) {
            FileUtils.delete(new File(v.getPath()));
        }
        return R.ok();
    }

    // 保存播放器地址
    @PostMapping("/videoPlay")
    public R videoPlay(@RequestBody VideoPlayer v) throws IOException {
        if (StringUtils.isNotBlank(v.getPath())) {
            v.setId(1);
            playerService.updateById(v);
            return R.ok();
        } else {
            return R.error("播放器地址不合法");
        }
    }

    // 保存播放器地址
    @GetMapping("/playerPath")
    public R getPlayerPath() {
        return R.ok(playerService.getById(1).getPath());
    }

    // 打开文件所在路径
    @PostMapping("/openPath")
    public R openPath(@RequestBody Map<String,String> pathMap) throws IOException {
        log.info(pathMap);
        // 创建 File 对象
        File file = new File(pathMap.get("path"));
        // 检查平台是否支持 Desktop 类
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            // 检查文件是否存在
            if (file.exists()) {
                    desktop.open(file.getParentFile());
            } else {
                String message = "文件不存在";
                return R.error(message);
            }
        } else {
            String message = "无法打开文件所在位置";
            return R.error(message);
        }
        return R.ok();
    }


}
